package com.furtherstar.auth.init.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.furtherstar.auth.dao.enums.Disabled;
import com.furtherstar.auth.dao.mapper.AuthUserMapper;
import com.furtherstar.auth.dao.mapper.UserSecretMapper;
import com.furtherstar.auth.dao.model.AuthUser;
import com.furtherstar.auth.dao.model.UserSecret;
import com.furtherstar.auth.init.dao.mapper.InitMapper;
import com.furtherstar.auth.init.dao.model.Init;
import com.furtherstar.auth.util.PasswordUtil;
import com.furtherstar.auth.util.SuperadminUtil;
import com.yummy.convention.lang.IDGenerator;
import com.yummy.web.security.bean.UserType;

@Service
public class InitService {
	
	@Autowired
	private InitMapper initMapper;
	@Autowired
	private AuthUserMapper authUserMapper;
	@Autowired
	private UserSecretMapper userSecretMapper;
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Transactional
	public void init() {
		Init init = initMapper.getAndLock();
		if(init == null) {
			logger.info("find app has not been inited,start to init");
			doInit();
			init = Init.create();
			initMapper.insert(init);
			logger.info("app inited");
		}
	}

	private void doInit() {
		AuthUser user = authUserMapper.selectByPrimaryKey(1L);
		if(user != null) {
			logger.info("find superadmin exist,do nothing.");
			return;
		}
		AuthUser superadmin = createSuperadmin();
		UserSecret userSecret = new UserSecret();
		userSecret.setId(IDGenerator.getId());
		userSecret.setPassword(PasswordUtil.encryptPassword("123456",superadmin.getId().toString()));
		userSecret.setUserid(superadmin.getId());
		userSecret.setUsername(superadmin.getUsername());
		authUserMapper.insert(superadmin);
		userSecretMapper.insert(userSecret);
	}

	private AuthUser createSuperadmin() {
		AuthUser user = new AuthUser();
		user.setId(SuperadminUtil.getId());
		user.setDisabled(Disabled.normal.ordinal());
		user.setNickname("超级管理员");
		user.setType(UserType.common.ordinal());
		user.setUsername("superadmin");
		return user;
	}

}
